import axios from 'axios';

var ajax = axios.create({
    baseURL: process.env.BASE_URL, //测试
    headers: {
        APPID: process.env.APPID,
    },
    withCredentials: true, //cookie
    crossDomain: true //跨域
});

//添加一个请求拦截器
ajax.interceptors.request.use(function(config) {
    //在请求发出之前进行一些操作
    var token = localStorage.getItem('token');
    if(token){
        config.headers['TOKEN'] = token
    }
    return config;
}, function(err) {
    console.error(err);
    alert('请求发生错误,请稍后再试!')
    //Do something with request error
    return Promise.reject(err);
});
//添加一个响应拦截器
ajax.interceptors.response.use(function(res) {
    var status = res.data.status;
    if(!status){
        alert(res.data.message)
        return Promise.reject(res.data.message)
    }
    return (res.data.data ? res.data.data : res.data.status);
}, function(err) {
    console.error(err);
    alert('响应发生错误,请稍后再试!')
    //Do something with response error
    return Promise.reject(err);
})

export const setNickName = name => {
    return ajax.put('userControlPanel/' + name);
};

export const getConfig = keys => {
    return ajax.get('config?keys=' + keys);
};
export const getMessages = () => {
    return ajax.get('message/passed');
};
export const postMessage = params => {
    return ajax.post('message', params);
};
export const postSMS = phoneNumber => {
    return ajax.post('sms/' + phoneNumber);
};
export const loginByCode = params => {
    return ajax.post('userControlPanel/loginByCode', params);
};
export const loginBySecretKey = params => {
    return ajax.post('userControlPanel/loginBySecretkey', params);
};
export const loginByUserCode = params => {
    return ajax.post('userControlPanel/loginByUserCode', params);
};
export const getLiveBannerList = () => {
    return ajax.get('/liveBanner')
}
